from PyQt5.QtCore import QObject
import define
import json


class ConfigManager(QObject):
    CONFIG_PATH = 'config.json'
    def __init__(self):
        self.config = {}
        self.word = ''
        self.show_number = 20
        self.function_consuming_time = []
        self.sentence_max_consuming_time = []
        self.sentence_max_time = []
        self.sort_type = define.SORT_FUNCTION_CONSUMING_TIME

    def dump(self):
        json_str = json.dump(self.get_dict())
        with open(self.CONFIG_PATH, 'w') as f:
            f.write(json_str)
    
    def get_dict(self):
        return {
            define.SELECTION: {
                define.WORD: self.word,
                define.SHOW_NUMBER: self.show_number,
                define.FUNCTION_CONSUMING_TIME: self.function_consuming_time,
                define.SENTENCE_MAX_CONSUMING_TIME: self.sentence_max_consuming_time,
                define.SENTENCE_MAX_TIME: self.sentence_max_time,
            },
            define.SORT_TYPE: self.sort_type
        }

    def load(self):
        try:
            with open(self.CONFIG_PATH, 'r') as f:
                json_str = f.read()
                selection = json_str[define.SELECTION]
                self.word = selection[define.WORD]
                self.show_number = selection[define.SHOW_NUMBER]
                self.function_consuming_time = selection[define.FUNCTION_CONSUMING_TIME]
                self.sentence_max_consuming_time = selection[define.SENTENCE_MAX_CONSUMING_TIME]
                self.sentence_max_time = selection[define.SENTENCE_MAX_TIME]
                self.sort_type = json_str[define.SORT_TYPE]
        except:
          print('An exception occurred')

g_config_manager = ConfigManager()

def get_config_manager():
    return g_config_manager